#!/bin/sh
#抽取日表数据到dws_first_receive_urea_pdi表中
CUR_DIR=$(cd "$(dirname "${BASH_SOURCE-$0}")"; pwd)
UP_DIR=$(dirname $(dirname $(dirname "$PWD")))
echo ${UP_DIR}
source ${UP_DIR}/system_env.sh


START_TIME=$(date +%s)
hive_db=${hive_db}

if [ -z "${hive_db}" ];then
  hive_db=dataplatform_trip
else
  hive_db=${hive_db}
fi


if [ -z "$1" ];then
  part_time=$(date -d "1 days ago" +%Y%m%d)
else
  part_time=$1
fi

sql_suffix=$(cat <<EOF
  insert into table ${hive_db}.dws_first_receive_urea_pdi
  select tid,route_start_time,standardMileage,standardFuelCons,from_unixtime(unix_timestamp() ,'yyyy-MM-dd HH:mm:ss')
  from (
  SELECT
      t1.tid as tid ,
      t1.route_start_time as route_start_time ,
      first_value(route_start_mileage) over (partition by t1.tid order by t1.route_start_time ) as standardMileage,
      first_value(route_start_fuel) over (partition by t1.tid order by t1.route_start_time ) as standardFuelCons,
      row_number() over (partition by t1.tid order by t1.route_start_time  desc) row_number
     from ${hive_db}.trip_statistics t1
     left join ${hive_db}.dws_first_receive_urea_pdi t2
      on (t1.tid = t2.tid )
   where t2.tid is null
   and t1.route_start_mileage >0
   and t1.route_start_fuel >0
   and t1.day = ${part_time}
       and nvl(t1.trip_urea,0) >0) a
  where row_number = 1;
EOF
)

CUR_DIR=$(cd "$(dirname "$0")"; pwd)
hive_config=$(cat  "${CUR_DIR}"/hive.config)
sql="${hive_config}${sql_suffix}"
echo "导入dws_first_receive_urea_pdi的SQL为：${sql}"

#执行语句·
hive -e "${sql}"
if [ $? -ne 0 ];then
  echo "导入dws_first_receive_urea_pdi失败，耗时$((`date +%s`-START_TIME))秒..."
else
  echo "导入dws_first_receive_urea_pdi成功，耗时$((`date +%s`-START_TIME))秒..."
fi